﻿using Microsoft.Win32;
using System;
using System.Globalization;
using System.IO;
using System.Windows.Forms;

namespace TipTip
{
    /// <summary>
    /// by longware@qq.com
    /// </summary>
    public partial class Form1 : Form
    {
        private int MinCounter = 0;
        private string configFile = Application.StartupPath + @"\config.ini";

        public Form1()
        {
            InitializeComponent();
            writeLog("启动软件---------------", true);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //read ini
            try
            {
                IniFiles ini = new IniFiles(configFile);
                if (!File.Exists(configFile))
                {
                    ini.WriteInteger("config", "min", 45);
                }
                tbMin.Value = ini.ReadInteger("config", "min", 45);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            //read boot
            chkBoxBoot.Checked = GetAutoRunByReg(Application.ExecutablePath);
            if (chkBoxBoot.Checked)
            {
                this.WindowState = FormWindowState.Minimized;
                btnStart_Click(sender,e);
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            MinCounter = 0;
            btnStart.Enabled = false;
            btnEnd.Enabled = true;
            timer1.Enabled = true;
            writeLog("启动闹钟，休息时限：" + tbMin.Value, true);

            //save ini
            try
            {
                IniFiles ini = new IniFiles(configFile);
                ini.WriteInteger("config", "min", Decimal.ToInt16(tbMin.Value));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnEnd_Click(object sender, EventArgs e)
        {
            btnEnd.Enabled = false;
            btnStart.Enabled = true;
            timer1.Enabled = false;
            writeLog("停止闹钟", true);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Text = "休息提醒闹钟 - 已经工作了 " + MinCounter + " 分钟";
            if (MinCounter == tbMin.Value)
            {
                ShowDesktop();
                writeLog("提醒休息", true);
                timer1.Enabled = false;

                using (TipForm tip = new TipForm(tbMin.Value.ToString()))
                {
                    tip.ShowDialog();
                }

                MinCounter = 0;
                timer1.Enabled = true;
            }
            else
            {
                MinCounter++;
            }
        }

        public void ShowDesktop()
        {
            Type shellType = Type.GetTypeFromProgID("Shell.Application");
            object shellObject = System.Activator.CreateInstance(shellType);
            shellType.InvokeMember("ToggleDesktop", System.Reflection.BindingFlags.InvokeMethod, null, shellObject, null);
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="msg">日志文本</param>
        /// <param name="add_datetime">是否添加时间戳</param>
        public static void writeLog(string msg, bool add_datetime)
        {
            string logfile = Application.StartupPath + "/log.txt";
            using (StreamWriter w = File.AppendText(logfile))
            {
                if (add_datetime)
                {
                    w.WriteLine("{0}\t {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo), msg);
                }
                else
                {
                    w.WriteLine("{0}", msg);
                }

                w.Flush();
                w.Close();
            }
        }

        #region  最小化隐藏


        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            //notifyIcon1.Visible = false;
            this.Show();
            WindowState = FormWindowState.Normal;
            this.Focus();
        }

        private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            writeLog("退出软件---------------", true);
            Application.Exit();
        }

        private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Powered by longware@qq.com", "提示");
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //注意判断关闭事件Reason来源于窗体按钮，否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;    //取消"关闭窗口"事件
                this.WindowState = FormWindowState.Minimized;    //使关闭时窗口向右下角缩小的效果
                notifyIcon1.Visible = true;
                notifyIcon1.ShowBalloonTip(3000, "提示", "程序未退出，它在这里!", ToolTipIcon.Info);
                this.Hide();
                return;
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)    //最小化到系统托盘
            {
                notifyIcon1.Visible = true;    //显示托盘图标
                notifyIcon1.ShowBalloonTip(3000, "提示", "程序未退出，它在这里!", ToolTipIcon.Info);
                this.Hide();    //隐藏窗口
            }
        }

        #endregion

        /// <summary>
        /// 设置应用程序开机自动运行
        /// </summary>
        /// <param name="fileName">应用程序的文件名</param>
        /// <param name="isAutoRun">是否自动运行,为false时，取消自动运行</param>
        /// <returns>返回1成功，非1不成功</returns>
        public static String SetAutoRunByReg(string fileName, bool isAutoRun)
        {
            string reSet = string.Empty;
            RegistryKey reg = null;
            try
            {
                if (!File.Exists(fileName))
                {
                    reSet = "设置/取消自动启动发生异常:" + fileName + "文件不存在!";
                }
                string key = @"Software\Microsoft\Windows\CurrentVersion\Run";
                string name = Path.GetFileName(fileName);
                reg = Registry.LocalMachine.OpenSubKey(key, true);
                if (reg == null)
                {
                    reg = Registry.LocalMachine.CreateSubKey(key);
                }
                if (isAutoRun)
                {
                    reg.SetValue(name, fileName);
                    reSet = "1";
                }
                else
                {
                    if (reg.GetValue(name) != null)
                    {
                        reg.DeleteValue(name);
                    }
                    reSet = "1";
                }

            }
            catch (Exception ex)
            {
                reSet = "设置/取消自动启动发生异常:[" + ex.Message + "],请尝试用管理员身份运行！";
            }
            finally
            {
                if (reg != null)
                {
                    reg.Close();
                }
            }
            return reSet;
        }

        //get boot
        public static bool GetAutoRunByReg(string fileName)
        {
            bool flag = false;
            RegistryKey reg = null;
            try
            {
                if (!File.Exists(fileName))
                {
                    return flag;
                }
                string key = @"Software\Microsoft\Windows\CurrentVersion\Run";
                reg = Registry.LocalMachine.OpenSubKey(key, false);
                if (reg == null)
                {
                    reg = Registry.CurrentUser.OpenSubKey(key, false);
                }
                if (reg == null)
                {
                    return flag;
                }
                string[] names = reg.GetValueNames();
                foreach (var item in names)
                {
                    //Console.WriteLine(item +"-----"+ reg.GetValue(item)+"-------");
                    int pos = reg.GetValue(item).ToString().IndexOf(fileName, StringComparison.CurrentCultureIgnoreCase);
                    if(pos > -1)
                    {
                        flag = true;
                        break;
                    }
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取是否自动启动发生异常:[" + ex.Message + "],请尝试用管理员身份运行！");
            }
            finally
            {
                if (reg != null)
                {
                    reg.Close();
                }
            }
            return flag;
        }


        //开机自动启动并最小化
        private void chkBoxBoot_Click(object sender, EventArgs e)
        {
            string res = SetAutoRunByReg(Application.ExecutablePath, chkBoxBoot.Checked);
            if (res != "1")
            {
                MessageBox.Show(res);
            }
        }
    }
}
